package com.xc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.domain.AjaxResult;
import com.xc.domain.dto.LoginBody;
import com.xc.domain.dto.LoginUser;
import com.xc.domain.pojo.SysUser;
import com.xc.domain.pojo.SysUserPost;
import com.xc.domain.pojo.SysUserRole;
import com.xc.mapper.SysUserMapper;
import com.xc.service.SysUserPostService;
import com.xc.service.SysUserRoleService;
import com.xc.service.SysUserService;
import com.xc.utils.JwtUtil;
import com.xc.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 *
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserPostService sysUserPostService;

    @Override
    public AjaxResult login(LoginBody loginBody) {

        // Authentication 封装 登录的用户信息
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());

        Authentication authenticate;
        try {
            // AuthenticationManager 用来做认证
            authenticate = authenticationManager.authenticate(token);
            // UserDetailsService
        } catch (AuthenticationException e){
            return AjaxResult.error("用户名或密码错误");
        }

        if (Objects.isNull(authenticate)){
            return AjaxResult.error("用户名或密码错误");
        }

        LoginUser loginUser= (LoginUser) authenticate.getPrincipal();

        // 生成token
        String jwt = JwtUtil.createJWT(loginUser.getSysUser().getUserId().toString());
        // 将jwt保存到redis
        redisCache.setCacheObject("login:"+loginUser.getSysUser().getUserId(),loginUser);
        return AjaxResult.success("登录成功",jwt);
    }

    @Override
    public AjaxResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser =(LoginUser) authentication.getPrincipal();
        if(Objects.isNull(loginUser)){
            return AjaxResult.error("未登录");
        }
        redisCache.deleteObject("login:"+loginUser.getSysUser().getUserId());
        return AjaxResult.success("退出成功");
    }

    @Override
    public Page<SysUser> userList(int page, int pageSize) {
        //分页参数
        Page<SysUser> rowPage = new Page(page, pageSize);

        //queryWrapper组装查询where条件
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        rowPage = this.baseMapper.selectPage(rowPage, queryWrapper);
        return rowPage;
    }

    @Override
    public AjaxResult select(Integer page, Integer pageSize, String userName, String phoneNumber, Integer status,String createTime, String endTime) {
        Page<SysUser> sysUserPage = new Page<SysUser>(page,pageSize);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (userName!=null){
            queryWrapper.like("user_name", userName);
        }else if (phoneNumber!=null){
            queryWrapper.like("phonenumber", phoneNumber);
        }else if (status!=null){
            queryWrapper.eq("status", status);
        }else if (createTime!=null){
            queryWrapper.between("create_time",createTime,endTime);
        }

        Page<SysUser> selectPage = this.baseMapper.selectPage(sysUserPage, queryWrapper);
        if (selectPage!=null){
            return AjaxResult.success("操作成功");
        }

        return AjaxResult.error("操作失败");

    }

    @Transactional
    @Override
    public AjaxResult add(SysUser sysUser) {
        int insert = this.baseMapper.insert(sysUser);
        if (insert>0){
            sysUserRoleService.add(new SysUserRole(sysUser.getUserId(),sysUser.getRoleId()));
            sysUserPostService.add(new SysUserPost(sysUser.getUserId(),sysUser.getPostId()));
            return AjaxResult.success("操作成功");
        }
        return AjaxResult.error("操作失败");
    }

    @Transactional
    @Override
    public AjaxResult update(SysUser sysUser) {
        int i = this.baseMapper.updateById(sysUser);
        if (i>0){
            sysUserRoleService.upd(new SysUserRole(sysUser.getUserId(),sysUser.getRoleId()));
            sysUserPostService.upd(new SysUserPost(sysUser.getUserId(),sysUser.getPostId()));
            return AjaxResult.success("操作成功");
        }
        return AjaxResult.error("操作失败");
    }

    @Override
    public AjaxResult del(SysUser sysUser) {
        sysUserRoleService.del(sysUser.getRoleId());
        sysUserPostService.del(sysUser.getPostId());
        int i = this.baseMapper.deleteById(sysUser.getUserId());
        if (i>0){
            return AjaxResult.success("操作成功");
        }

        return AjaxResult.error("操作失败");
    }
}
